package com.xuge.common.resolver;

import com.xuge.common.annotation.LoginUser;
import com.xuge.common.jwt.JWTUtils;
import com.xuge.pojo.UserInfoEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private JWTUtils jwtUtils;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserInfoEntity.class)&&parameter.hasParameterAnnotation(LoginUser.class);
    }

    /**
     * 解析user注解 返回登录的user信息
     * @param parameter
     * @param mavContainer
     * @param webRequest
     * @param binderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
//        //开始封装user信息
//        String userId = webRequest.getParameter("userId");
//        //从数据库获取信息
//        UserEntry userEntry = new UserEntry();
//        userEntry.setAge("12");
//        userEntry.setName("smile");
//        return userEntry;
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        //String token = webRequest.getHeader("token");
        String token = ((ServletWebRequest) webRequest).getResponse().getHeader("token");
        if (StringUtils.isBlank(token)){
            return userInfoEntity;
        }
        return  jwtUtils.getUserInfo(token);
    }
}
